package com.common.app.utls.network

import android.app.Application
import android.os.Build
import android.text.TextUtils
import com.common.app.helper.UserHelper
import com.common.app.helper.UserHelper.getToken
import com.common.app.utls.Constants
import com.common.app.utls.Utils
import com.common.app.utls.Utils.getDisplayMetrics
import com.common.app.utls.network.gson.DoubleDefault0Adapter
import com.common.app.utls.network.gson.IntegerDefault0Adapter
import com.common.app.utls.network.gson.LongDefault0Adapter
import com.common.app.utls.network.interceptor.HeadUrlInterceptor
import com.common.app.utls.network.interceptor.HeadersInterceptorsConfig
import com.common.app.utls.network.interceptor.HeadersInterceptorsConfig.getInterceptorsConFig
import com.common.app.utls.network.interceptor.RequestUpHealthDataInterceptor
import com.common.app.utls.network.interceptor.TokenInterceptor
import com.common.base.app.extras.otherwise
import com.common.base.app.extras.yes
import com.common.base.security.AESEncrypt
import com.common.base.utils.AppUtils
import com.common.base.utils.AppUtils.getSource
import com.common.base.utils.JsonUtils
import com.common.base.utils.VersionUtils
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import rxhttp.RxHttpPlugins
import rxhttp.wrapper.converter.GsonConverter
import rxhttp.wrapper.cookie.CookieStore
import rxhttp.wrapper.ssl.HttpsUtils
import java.io.File
import java.io.IOException
import java.net.Proxy
import java.net.URLEncoder
import java.util.Date
import java.util.concurrent.TimeUnit
import javax.net.ssl.SSLSession

/**
 * 作者：sosou
 * <p>
 * 版本：1.0
 * <p>
 * 创建日期：2022/8/19
 * <p>
 * 描述：http初始化管理
 * <p>
 * 修订历史：
 */
object RxHttpManager {

    private var gson: Gson? = null
    private const val DEFAULT_TIMEOUT = 5L

    fun init(context: Application, isDebug: Boolean) {

        val converter = GsonConverter.create(buildGson())
        val file = File(context.externalCacheDir, "RxHttpCookie")
        val sslParams = HttpsUtils.getSslSocketFactory()
        val clientBuilder: OkHttpClient.Builder = OkHttpClient.Builder()
            .cookieJar(CookieStore(file))
            .proxy(Proxy.NO_PROXY)//禁用网络代理（防止抓包）
//            .addInterceptor(TokenInterceptor())
//            .addInterceptor(WyTokenInterceptor())
            .addInterceptor(HeadUrlInterceptor())
            .addInterceptor(RequestUpHealthDataInterceptor())
            .addNetworkInterceptor(ResponseInterceptor())
            .connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
            .readTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
            .writeTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
            .sslSocketFactory(sslParams.sSLSocketFactory, sslParams.trustManager) //添加信任证书
            .hostnameVerifier { hostname: String?, session: SSLSession? -> true } //忽略host验证

        //设置数据解密/解码器，非必须
//        RxHttp.setResultDecoder(s -> s);

        //设置全局的转换器，非必须
//        RxHttp.setConverter(FastJsonConverter.create());

        //设置缓存策略，非必须
//        val cacheFile = File(context.externalCacheDir, "RxHttpCache")

        //设置公共参数，非必须
        RxHttpPlugins.init(clientBuilder.build())
            .setDebug(isDebug)
//            .setCache(
//                cacheFile,
//                (1000 * 100).toLong(),
//                CacheMode.REQUEST_NETWORK_FAILED_READ_CACHE
//            )
//            .setResultDecoder { s: String? -> s } //设置数据解密/解码器，非必须
            .setConverter(converter)
    }

    /**
     * 增加后台返回""和"null"的处理
     * 1.int=>0
     * 2.double=>0.00
     * 3.long=>0L
     *
     * @return
     */
    private fun buildGson(): Gson? {
        if (gson == null) {
            gson = GsonBuilder()
                .registerTypeAdapter(Int::class.java, IntegerDefault0Adapter())
                .registerTypeAdapter(Int::class.javaPrimitiveType, IntegerDefault0Adapter())
                .registerTypeAdapter(Double::class.java, DoubleDefault0Adapter())
                .registerTypeAdapter(Double::class.javaPrimitiveType, DoubleDefault0Adapter())
                .registerTypeAdapter(Long::class.java, LongDefault0Adapter())
                .registerTypeAdapter(Long::class.javaPrimitiveType, LongDefault0Adapter())
                .create()
        }
        return gson
    }
}